<?php

Class Controller_Person Extends Controller_Base {
	function index() {
		// just for test
	}

	public function grid() {
		$page = $_POST['page'];
		// get the requested page
		$limit = $_POST['rows'];
		// get how many rows we want to have into the grid
		$sidx = $_POST['sidx'];
		// get index row - i.e. user click to sort
		$sord = $_POST['sord'];
		// get the direction
		if(!$sidx)
			$sidx = 1;

		$result = Person::get(DB::$db, -1, "", "count(*) as count");
		//DB::query("SELECT COUNT(*) AS count FROM person");
		$count = $result[0]['count'];

		if($count > 0) {
			$total_pages = ceil($count / $limit);
		} else {
			$total_pages = 0;
		}
		if($page > $total_pages)
			$page = $total_pages;
		$start = $limit * $page - $limit;
		// do not put $limit*($page - 1)
		$SQL = "SELECT * from person ORDER BY $sidx $sord LIMIT $start , $limit";
		$result = DB::query($SQL);

		$responce -> page = $page;
		$responce -> total = $total_pages;
		$responce -> records = $count;
		$i = 0;
		$admin = User::checkAccess("admin");
		foreach($result as $i => $row) {
			$reports = Report::get(null, "", -1, "`author`='" . $row['id'] . "'", "`name`,`id`");
			$row['reports'] = "";
			$comma = "";
			foreach($reports as $report) {
				$row['reports'] .= $comma . Report::getMainLinkButton($report['name'], $report['id']);
				$comma = ",<br>";
			}
			if($row['reports'] == "")
				$row['reports'] = "У данного участника нет докладов.";
			$fio = Person::getFio($row);
			$responce -> rows[$i]['id'] = $row['id'];
			//$row['degree']
			$cell = array($fio, ($row['state'] == 0 ? "<div class='ui-state-error'>Нет в сети</div>" : "<div class='ui-state-highlight'>Есть в сети</div>"), $row['reports']);
			if($admin) {
				$cell[] = "<a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a>";
			}
			$responce -> rows[$i]['cell'] = $cell;
		}
		echo json_encode($responce);
	}

	function loadPhoto() {
		// Проверяем загружен ли файл
		$sizeLimit = $isAvailableImgFormat = null;
		if(!(isset($_FILES['logo'])&&isset($_FILES['logo']['name'])&&isset($_FILES['logo']['size'])&&$_FILES['logo']['size']>0)){
			$isAvailableImgFormat = "Ошибка загрузки файла!";	
		}
		if(!(User::checkAccess('user')&&($_SESSION['user']['state']!=0||User::checkAccess('admin')))){
			$isAvailableImgFormat = "Ощибка доступа!";
		}
		$type 					= preg_replace("/^([^\.]+)/", "", $_FILES['logo']['name']);
		$isAvailableImgFormat 	= isAvailableImgFormat($type);
		$sizeLimit 				= $_FILES['logo']['size']>1024*1024*20?"Размер фоторграфии слишком велик. Максимально допустимый размер 20 Мб.":1;
		if(is_uploaded_file($_FILES["logo"]["tmp_name"])&&$isAvailableImgFormat==1&&$sizeLimit==1) {
			$name = $_SESSION['user']['login'] . $type;
			$path = "static/img/user/" . $name;
			$source_path = "static/img/user/source/" . $name;
			move_uploaded_file($_FILES["logo"]["tmp_name"], $path);
			$res = array();
			list($res['width'], $res['height'], $type, $res['attr']) = getImageSize($path);

			

			if($res['width']>500) {
				$xscale = $res['width'] / 500;
				Img_::image_resize($path, "", 500,round($res['height']*(1/$xscale)));
				list($res['width'], $res['height'], $type, $res['attr']) = getImageSize($path);
			}
			copy($path,$source_path);

			$res['state'] = 1;
			$res['msg'] = "Фотография успешно загружена!";
			$res['path'] = $path . "?r=" . rand(100, 10000);
			$_SESSION['logo'] = $name;
			echo json_encode($res);
		} else {
			$res['state'] = 0;
			$res['msg'] = "";
			$res['msg'].= ($sizeLimit!=1?$sizeLimit."<br>":"").($isAvailableImgFormat!=1?$isAvailableImgFormat."<br>":"");
			echo json_encode($res);
		}
	}

	function edit() {
		//Если пользователь не авторизован тогда выдаём ошибку
		if(!User::checkAccess('user'))
			die('Ошибка доступа!!!');
		$db = DB::get();
		$d = $_POST;
		if(isset($d['form']) == true) {
			$u = $_SESSION['user'];
			$s = $_SESSION['user']['person'];
			$s['countries'] = Country::getSelect($s['country']);
			$s['short_name'] = Person::getFio($s);
			$s['logo'] = $u['logo'];
			$s['date'] = date('Y-m-d H:i:s');
			$s['degree_1'] = isset($s['degree']) && $s['degree'] != "" ? "<div><span class='b'>Звание:</span> " . $s['degree'] . "</div>" : "";
			$s['post_1'] = isset($s['post']) && $s['post'] != "" ? "<div><span class='b'>Должность:</span> " . $s['post'] . "</div>" : "";
			$s['img_size'] = getimagesize("static/img/user/" . $u['logo']);
			$s['img_size'] = $s['img_size'][3];
			$res["title"] = "Редактирование личной информации пользователя";
			$res["html"] = Template::parse_("person/edit", $s);

			echo json_encode($res);
		} else {
			$res = array("state" => true, "error" => array(), "action" => "set");
			$v = Person::validate($res, $db);
			if($v['state']) {
				if(isset($_SESSION['logo']) && is_file("static/img/user/" . $_SESSION['logo'])) {
					if($_SESSION['user']['logo'] != $_SESSION['logo']&&$_SESSION['user']['logo']!='noavatar.png') {
						if(is_readable("static/img/user/" . $_SESSION['user']['logo']))unlink("static/img/user/" . $_SESSION['user']['logo']);
						if(is_readable("static/img/user/source/" . $_SESSION['user']['logo']))unlink("static/img/user/source/" . $_SESSION['user']['logo']);
						if(is_readable("static/img/user/min/" . $_SESSION['user']['logo']))unlink("static/img/user/min/" . $_SESSION['user']['logo']);
						if(is_readable("static/img/user/mid/" . $_SESSION['user']['logo']))unlink("static/img/user/mid/" . $_SESSION['user']['logo']);
					}
					$_SESSION['user']['logo'] = $_SESSION['logo'];
					User::set( array('logo' => $_SESSION['logo']));
					$path = "static/img/user/" . $_SESSION['logo'];
					Img_::image_resize($path);
					Img_::image_resize($path, "static/img/user/min/" . $_SESSION['logo'], 30, 30);
					Img_::image_resize($path, "static/img/user/mid/" . $_SESSION['logo'], 66, 66);
				}
				$s = Person::set($_POST['person'], $db);
				$res = array("state" => true, "msg" => "Редактирование личной информации прошло успешно!");
				echo json_encode($res);
			} else {
				echo json_encode($v);
			}
		}
	}

}

function isAvailableImgFormat($type){
	$type = strtolower($type);
	if($type == 'jpeg')$type = 'jpg';
	switch($type) {
		case '.bmp' :
			return 1;
			break;
		case '.gif' :
			return 1;
			break;
		case '.jpg' :
			return 1;
			break;
		case '.png' :
			return 1;
			break;
		default :
			return "Данный '$type' формат не поддерживается!<br>Поддерживаемые форматы - jpg,bmp,gif,png.";
	}
}
?>